package com.junlong0716.enjoylearning.ui

import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.TextUtils
import android.view.LayoutInflater
import com.jakewharton.rxbinding2.widget.RxTextView
import com.junlong0716.enjoylearning.R
import com.junlong0716.enjoylearning.adapter.ChannelListAdapter
import com.junlong0716.enjoylearning.constant.NetConstant
import com.junlong0716.enjoylearning.entity.AudioEntity
import com.junlong0716.enjoylearning.entity.ChannelMultipleItemEntity
import com.junlong0716.enjoylearning.net.api.NetApi
import com.junlong0716.enjoylearning.service.MusicService
import com.junlong0716.enjoylearning.service.PlayerManager
import com.junlong0716.enjoylearning.widget.PlayerBarView
import com.junlong0716.getknowledgedemo.decoration.DividerItemDecoration
import com.junlong0716.module.common.rxbus.RxBus
import com.lzy.okgo.OkGo
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_search.*
import org.json.JSONObject
import java.util.concurrent.TimeUnit

class SearchActivity : AppCompatActivity() {
    private lateinit var data: ArrayList<ChannelMultipleItemEntity>
    private lateinit var channelListAdapter: ChannelListAdapter

    private var mPlayerBarView: PlayerBarView? = null
    private var musicService: MusicService? = null
    private var mPlayerManager: PlayerManager? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_search)
        RxBus.getDefault().register(this)
        bindMyService()
        data = ArrayList()
        rv_search_history.layoutManager = LinearLayoutManager(this)
        rv_search_history.addItemDecoration(DividerItemDecoration(this, LinearLayoutManager.VERTICAL, 4, ContextCompat.getColor(this, R.color.recyclerview_divider_gray)))
        setOnRecyclerViewScrollDirectListener(rv_search_history)
        channelListAdapter = ChannelListAdapter(data)
        rv_search_history.adapter = channelListAdapter
        RxTextView.textChanges(det_search)
                .skip(1)
                .debounce(800, TimeUnit.MILLISECONDS)
                .filter { t -> !TextUtils.isEmpty(t) }
                .switchMap { t -> Observable.just(requestSearch(t.toString())) }
                .subscribeOn(Schedulers.io())
                //界面更新在主线程
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe { t ->
                    data.clear()
                    if (t.isEmpty()) {
                        channelListAdapter.emptyView = LayoutInflater.from(this).inflate(R.layout.view_empty, null)
                    } else {
                        data.addAll(t)
                    }
                    channelListAdapter.notifyDataSetChanged()
                }


        channelListAdapter.setOnItemClickListener { adapter, view, position ->
            when (adapter.getItemViewType(position)) {
                ChannelMultipleItemEntity.ITEM_TYPE_AUDIO -> {
                    val audioEntity = AudioEntity(data[position].id, NetConstant.REQUEST_SOURCE + data[position].fileAddress, data[position].knowledgeTitle, NetConstant.REQUEST_SOURCE + data[position].coverImg)
                    mPlayerManager!!.playMusic(audioEntity)
                }
                ChannelMultipleItemEntity.ITEM_TYPE_VIDEO -> {
                    //跳转到视频播放
                    val intent = Intent()
                    intent.setClass(this, VideoActivity::class.java)
                    intent.putExtra("video_url", NetConstant.REQUEST_SOURCE + data[position].fileAddress)
                    intent.putExtra("video_id", data[position].id)
                    intent.putExtra("video_author", data[position].authorName)

                    startActivity(intent)
                }
                ChannelMultipleItemEntity.ITEM_TYPE_DOCUMENT -> {
                    //跳转到文稿页面
                    val intent = Intent()
                    intent.setClass(this, WebActivity::class.java)
                    intent.putExtra("document_url", NetConstant.REQUEST_SOURCE + data[position].fileAddress)
                    intent.putExtra("document_title", data[position].knowledgeTitle)
                    intent.putExtra("document_id", data[position].id)
                    startActivity(intent)
                }
            }
        }

    }

    private var conn = object : ServiceConnection {
        override fun onServiceDisconnected(name: ComponentName?) {

        }

        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            val myBinder = service as (MusicService.MyBinder)
            musicService = myBinder.getService()
            mPlayerManager = musicService!!.getPlayerManager()
            mPlayerBarView = PlayerBarView(this@SearchActivity, mPlayerManager!!, rl_container)
        }
    }

    private fun bindMyService() {
        val intent = Intent(this, MusicService::class.java)
        bindService(intent, conn, AppCompatActivity.BIND_AUTO_CREATE)
    }


    private fun requestSearch(searchValue: String): ArrayList<ChannelMultipleItemEntity> {
        val data = ArrayList<ChannelMultipleItemEntity>()
        val map = HashMap<String, Any>()
        map["title"] = searchValue
        val jsonObj = JSONObject(map)
        val response = OkGo.post<String>(NetConstant.REQUEST_HEADER + NetApi.API_QUERY_KNOWLEDGE_LIST)
                .tag(this)
                .upJson(jsonObj)
                .execute()
        try {
            val jsonObject = JSONObject(response.body()!!.string())
            val jsonArray = jsonObject.getJSONObject("data").getJSONArray("list")
            for (i in 0 until jsonArray.length()) {
                val id = jsonArray.getJSONObject(i).getInt("id")
                val knowledgeType = jsonArray.getJSONObject(i).getInt("knowledgeType")
                val knowledgeTitle = jsonArray.getJSONObject(i).getString("knowledgeTitle")
                val knowledgeContent = jsonArray.getJSONObject(i).getString("knowledgeContent")
                val knowledgeDescribe = jsonArray.getJSONObject(i).getString("knowledgeDescribe")
                val knowledgeAuthor = jsonArray.getJSONObject(i).getString("knowledgeAuthor")
                val coverImg = jsonArray.getJSONObject(i).getString("coverImg")
                val fileAddress = jsonArray.getJSONObject(i).getString("fileAddress")
                val browseNumber = jsonArray.getJSONObject(i).getString("browseNumber")
                val praiseNumber = jsonArray.getJSONObject(i).getInt("praiseNumber")
                val commentNumber = jsonArray.getJSONObject(i).getString("commentNumber")
                val specialId = jsonArray.getJSONObject(i).getString("specialId")
                val createDate = jsonArray.getJSONObject(i).getLong("createDate")
                val remarks = jsonArray.getJSONObject(i).getString("remarks")
                val authorName = jsonArray.getJSONObject(i).getString("authorName")
                data.add(ChannelMultipleItemEntity(id, knowledgeType, knowledgeTitle, knowledgeDescribe
                        , knowledgeContent, knowledgeAuthor, coverImg, praiseNumber, fileAddress, browseNumber,
                        commentNumber, specialId, createDate, authorName, ""))
            }
        } catch (e: Exception) {

        }
        return data
    }


    private fun setOnRecyclerViewScrollDirectListener(rvList: RecyclerView) {
        rvList.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
                if (dy > 0) {
                    //todo 隐藏播放布局
                    if (Math.abs(dy) > 2) {
                        if (mPlayerManager!!.getPlayerBarVisibilityState()) {
                            mPlayerBarView!!.setPlayerBarVisibility(false)
                        }
                    }

                } else {
                    //todo 显示播放布局
                    if (Math.abs(dy) > 2) {
                        if (mPlayerManager!!.getPlayerBarVisibilityState()) {
                            mPlayerBarView!!.setPlayerBarVisibility(true)
                        }
                    }
                }
            }
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        if (RxBus.getDefault().isRegistered(this)) {
            RxBus.getDefault().unregister(this)
        }

        mPlayerBarView = null

        unbindService(conn)
    }
}
